package com.song.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.song.common.base.UserContextInfo;
import com.song.common.response.PageInfo;
import com.song.framework.context.ContextUserInfoThreadHolder;
import com.song.framework.exception.ServiceException;
import com.song.module.admin.entity.ApChef;
import com.song.module.admin.entity.ApUserChefOrder;
import com.song.module.admin.mapper.ApChefMapper;
import com.song.module.admin.response.ApChefAppointmentResponse;
import com.song.module.admin.response.ApUserChefRecordResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.song.module.admin.request.ApUserChefRecordRequest;
import org.springframework.stereotype.Service;
import com.song.module.admin.mapper.ApUserChefRecordMapper;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.song.module.admin.service.IApUserChefOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 厨师预约记录业务层处理
 *
 * @author song
 * @date 2024-03-08
 */
@Slf4j
@Service
@AllArgsConstructor
public class ApUserChefOrderServiceImpl implements IApUserChefOrderService {

    private final ApUserChefRecordMapper baseMapper;

    private final ApChefMapper apChefMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApUserChefOrder add(ApUserChefRecordRequest request) {
        ApUserChefOrder entity = ApUserChefOrder.builder().build();
        BeanUtils.copyProperties(request, entity);
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(ApUserChefRecordRequest request) {
        ApUserChefOrder entity = ApUserChefOrder.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public ApUserChefOrder getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<ApUserChefRecordResponse> pageList(ApUserChefRecordRequest request) {
        Page<ApUserChefOrder> page = new Page<>(request.getPageNo(), request.getPageSize());
        IPage<ApUserChefRecordResponse> pageRecord = baseMapper.selectAppointmentPage(page, request);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<ApUserChefOrder> list(ApUserChefRecordRequest request) {
        LambdaQueryWrapper<ApUserChefOrder> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    @Override
    public List<ApChefAppointmentResponse> appointmentRecord(ApUserChefRecordRequest request) {
        UserContextInfo info = ContextUserInfoThreadHolder.get();
        List<ApUserChefOrder> list = baseMapper.selectList(Wrappers.lambdaQuery(ApUserChefOrder.class)
                .eq(ApUserChefOrder::getUserId, info.getId()).orderByDesc(ApUserChefOrder::getAppointmentTime));
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<Long> chefIds = list.stream().map(ApUserChefOrder::getChefId).collect(Collectors.toList());
        List<ApChef> apChefs = apChefMapper.selectList(Wrappers.lambdaQuery(ApChef.class).in(ApChef::getId, chefIds));
        Map<Integer, ApChef> chefMap = apChefs.stream().collect(Collectors.toMap(ApChef::getId, Function.identity()));
        return list.stream().map(x -> {
            System.out.println("chef"+x);
            ApChefAppointmentResponse response = new ApChefAppointmentResponse();
            response.setAppointmentTime(x.getAppointmentTime());
            response.setMeals(x.getMeals());
            response.setStatus(x.getStatus());
            response.setAddress(x.getAddress());
            response.setTelPhone(x.getTelPhone());
            ApChef apChef = chefMap.get(x.getChefId().intValue());
            if (Objects.nonNull(apChef)) {
                BeanUtils.copyProperties(apChef, response);
            }
            return response;
        }).collect(Collectors.toList());
    }

    @Override
    public void appointment(ApUserChefRecordRequest request) {
        UserContextInfo info = ContextUserInfoThreadHolder.get();
        ApUserChefOrder apUserChefOrder = baseMapper.selectOne(Wrappers.lambdaQuery(ApUserChefOrder.class)
                .eq(ApUserChefOrder::getChefId, request.getChefId())
                .eq(ApUserChefOrder::getAppointmentTime, request.getAppointmentTime())
                .eq(ApUserChefOrder::getMeals, request.getMeals())
                .eq(ApUserChefOrder::getUserId, info.getId()));
        if (Objects.nonNull(apUserChefOrder)) {
            throw new ServiceException("当前厨师已预约");
        }
        ApUserChefOrder record = ApUserChefOrder.builder()
                .chefId(request.getChefId())
                .appointmentTime(request.getAppointmentTime())
                .meals(request.getMeals())
                .price(request.getPrice())
                .address(request.getAddress())
                .telPhone(request.getTelPhone())
                .status(2)
                .userId(info.getId()).build();
        baseMapper.insert(record);
        // 增加预约人数
        Long chefId = request.getChefId();
        ApChef apChef = apChefMapper.selectById(chefId);
        if (Objects.nonNull(apChef)) {
            apChef.setReservationCount(apChef.getReservationCount() + 1);
            apChefMapper.updateById(apChef);
        }
    }


    private LambdaQueryWrapper<ApUserChefOrder> buildWrapper(ApUserChefRecordRequest param) {
        LambdaQueryWrapper<ApUserChefOrder> query = new LambdaQueryWrapper<>();
        return query;
    }

}
